package com.example.zhunongzonghe.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhunongzonghe.beans.SysRegionBean;
import com.example.zhunongzonghe.dao.SysRegionMapper;
import com.example.zhunongzonghe.entity.SysRegion;
import com.example.zhunongzonghe.service.ISysRegionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class SysRegionServiceImpl extends ServiceImpl<SysRegionMapper, SysRegion> implements ISysRegionService {

    @Autowired
    SysRegionMapper sysRegionMapper;
    @Override
    public List<SysRegionBean> getRegionTree() {
        // 获取所有区域
        List<SysRegion> allRegions = sysRegionMapper.selectList(null);
        // 用于按父 ID 分组区域的 Map
        Map<String, List<SysRegionBean>> regionMap = new HashMap<>();

        // 将 SysRegion 转换为 SysRegionBean，并按父 ID 分组
        allRegions.stream()
                .map(this::convertToBean)
                .forEach(regionBean -> regionMap
                        .computeIfAbsent(regionBean.getRegionParentId(), k -> new ArrayList<>())
                        .add(regionBean));

        // 递归构建树
        return buildChildren("-1", regionMap);
    }

    // 将 SysRegion 转换为 SysRegionBean 的辅助方法
    private SysRegionBean convertToBean(SysRegion sysRegion) {
        SysRegionBean sysRegionBean = new SysRegionBean();
        BeanUtils.copyProperties(sysRegion, sysRegionBean);
        return sysRegionBean;
    }

    // 递归构建树结构的方法
    private List<SysRegionBean> buildChildren(String regionParentId, Map<String, List<SysRegionBean>> regionMap) {
        // 根据父 ID 获取子节点列表
        List<SysRegionBean> children = regionMap.getOrDefault(regionParentId, Collections.emptyList());

        // 遍历子节点列表
        for (SysRegionBean child : children) {
            // 递归获取孙子节点列表
            List<SysRegionBean> grandchildren = buildChildren(child.getRegionId(), regionMap);
            // 如果存在孙子节点，则将孙子节点列表设置为子节点的 children 属性
            if (!grandchildren.isEmpty()) {
                child.setChildren(grandchildren);
            }
        }

        return children;
    }
}
